package com.app.backend.common.base;

import com.alibaba.fastjson.JSONObject;
import com.app.backend.common.annotation.InvokeLog;
import com.app.backend.common.response.BaseResponse;
import com.app.backend.common.utils.PageUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.Serializable;
import java.util.List;

/**
 * @program: BaseController
 * @description:
 * @author: Zhun.Xiao
 * @create: 2020-02-08 13:24
 **/
public abstract class BaseController<T, ID extends Serializable> {

    @Autowired
    protected abstract BaseService<T, ID> getService();

    @PostMapping(value = "/get")
    @ResponseBody
    @ApiOperation(value = "通过id获取")
    public BaseResponse<T> get(@RequestBody JSONObject jsonObject) {
        ID id = (ID) jsonObject.get("id");
        T entity = getService().get(id);
        return new BaseResponse<T>(entity);
    }

    @PostMapping(value = "/getAll")
    @ResponseBody
    @ApiOperation(value = "获取全部数据")
    public BaseResponse<List<T>> getAll() {
        List<T> list = getService().getAll();
        return new BaseResponse<List<T>>(list);
    }

    @PostMapping(value = "/getByPage")
    @ResponseBody
    @ApiOperation(value = "分页获取")
    public BaseResponse<Page<T>> getByPage(@RequestBody PageEntity page) {
        Page<T> data = getService().findAll(PageUtil.initPage(page));
        return new BaseResponse<Page<T>>(data);
    }

    @PostMapping(value = "/save")
    @ResponseBody
    @ApiOperation(value = "保存数据")
    @InvokeLog(persistence = true, description = "保存数据")
    public BaseResponse<T> save(@RequestBody T entity) {
        T t = getService().save(entity);
        return new BaseResponse<T>(t);
    }

    @PostMapping(value = "/update")
    @ResponseBody
    @ApiOperation(value = "更新数据")
    public BaseResponse<T> update(@RequestBody T entity) {
        T t = getService().update(entity);
        return new BaseResponse<T>(t);
    }

    @PostMapping(value = "/delByIds")
    @ResponseBody
    @ApiOperation(value = "批量通过id删除")
    public BaseResponse<T> delAllByIds(@RequestBody ID[] ids) {
        for (ID id : ids) {
            getService().deleteById(id);
        }
        return new BaseResponse();
    }


}